package com.bum.rss.bo;

import java.net.URI;
import java.net.URL;

import org.apache.commons.lang.StringUtils;

import com.bum.base.util.Base64Utils;
import com.bum.rss.site.util.BaseParser;

public class MediaHelper {
	public static final String	MEDIA_CODE_PREFIX	= "##";

	public static String cleanImg(String html, String base) {
		html = BaseParser.splitImg(html);
		base = BaseParser.getBaseUrl(html, base);

		String[] parts = html.split("\n");
		for (int i = 0, n = parts.length; i < n; i++) {
			parts[i] = parts[i].replaceAll("[`']", "\"");
			String lowerCode = parts[i].toLowerCase();
			if (lowerCode.startsWith("<img")) {
				String imgUrl = parseImageUrl(parts[i], base);
				if (StringUtils.isNotBlank(imgUrl) && imgUrl.startsWith("http")) {
					parts[i] = MEDIA_CODE_PREFIX + Base64Utils.encode(imgUrl) + "#";
				} else {
					parts[i] = "";
				}
			}
		}

		html = StringUtils.join(parts, "\n");
		return html;
	}
	
	public static void main(String[] args) {
		String url = "http://m.baomoi.com/avatar.aspx?ts=0&tt=1&ru=http%3a%2f%2fimg-hcm.24hstatic.com%2fupload%2f2-2014%2fimages%2f2014-06-07%2f1402116582-saoviet--2-.jpg";
		String code = Base64Utils.encode(url);
		System.out.println(new String(Base64Utils.decode(code)));
	}

	static String parseImageUrl(String html, String base) {
		String srcRegex = ".+?src=['\"](.*?)['\"].*";
		if (!html.matches(srcRegex)) {
			return null;
		}
		String imgUrl = html.replaceFirst(srcRegex, "$1");
		if (StringUtils.isBlank(imgUrl)) {
			return null;
		}

//		return getAbsoluteImgUrl(imgUrl, base);
		return imgUrl;
	}

	static String getAbsoluteImgUrl(String imgUrl, String base) {
		if (StringUtils.isBlank(imgUrl)) {
			return null;
		}

		URL url = null;
		try {
			URI uri = new URI(null, imgUrl, null);
			if (StringUtils.isNotBlank(base)) {
				url = new URL(new URL(base), uri.toASCIIString());
			} else {
				url = new URL(uri.toASCIIString());
			}

		} catch (Exception e) {
		}

		return null == url ? imgUrl : url.toString();
	}
}
